<template>
  <div class="app-container">
    <el-form :model="form" ref="form" label-width="100px" element-loading-text="玩命加载中" :rules="rules">
      <el-form-item label="学科：" prop="sid" required>
        <el-select v-model="form.sid" filterable placeholder="学科" @change="change"
                   style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">
          <el-option v-for="item in subjectFilter" :key="item.sid" :value="item.sid"
                     :label="item.subName+' ( '+item.uid+' )'"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="知识点" prop="point" required>
        <el-select v-model="form.point" multiple placeholder="请选择">
          <el-option v-for="(item,index) in points" :key="index" :label="item.point" :value="item.pid"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题干：" prop="stem" required>
        <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 10}" placeholder="请输入题干" v-model="form.stem"
                  suffix-icon="el-icon-edit" @focus="inputClick(form,'stem')"
                  style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)"/>
      </el-form-item>
      <el-form-item label="解析：" prop="analysis">
        <el-input type="textarea" v-model="form.analysis" suffix-icon="el-icon-edit"
                  @focus="inputClick(form,'analysis')" :autosize="{ minRows: 5, maxRows: 10}" placeholder="请输入解析"
                  style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)"/>
      </el-form-item>
      <el-form-item label="答案：" prop="answer" required>
        <!-- <el-input  type="textarea" v-model="form.answer" suffix-icon="el-icon-edit" @focus="inputClick(form,'analysis')" :autosize="{ minRows: 5, maxRows: 10}" placeholder="请输入解析" style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)" /> -->
        <el-form-item v-for="item in form.answer" :key="item.name" required label-width="50px"
                      class="question-item-label">
          <el-input v-model="item.content" suffix-icon="el-icon-edit" @focus="inputClick(item,`content`)"
                    class="question-item-content-input"/>
        </el-form-item>
      </el-form-item>
      <el-form-item label="分数：" prop="mark" required>
        <el-input-number v-model="form.mark" :precision="1" :step=".5" :max="100"></el-input-number>
      </el-form-item>
      <el-form-item label="难度：" required>
        <el-rate v-model="form.difficulty" class="question-item-rate" :colors="colors"></el-rate>
      </el-form-item>
      <el-form-item label="是否共享:" prop="share">
          <el-checkbox v-model="form.share" border>共享</el-checkbox>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="success" @click="questionItemAdd">添加答案</el-button>
        <el-button type="success" @click="showQuestion">预览</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="richEditor.dialogVisible" append-to-body :close-on-click-modal="false"
               style="width: 100%;height: 100%" :show-close="false" center>
      <Ueditor @ready="editorReady"></Ueditor>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editorConfirm">确 定</el-button>
        <el-button @click="richEditor.dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-drawer size="40%" direction="rtl" :visible.sync="questionShow.dialog" style="width: 100%;height: 100%">
      <QuestionShow :qType="2" :question="questionShow.question" :qLoading="questionShow.formLoading"/>
    </el-drawer>
  </div>
</template>

<script>
import axios from 'axios'
import QuestionShow from '../components/Show'
import Ueditor from '../Ueditor'  //用于编辑框的文本处理
import {getCourse, getKnowledge} from "../../api/data";

export default {
  components: {
    Ueditor, QuestionShow
  },

  mounted() {
    getCourse().then(res => {
      this.subjectFilter = res.data;
    })
  },
  data() {
    return {
      colors: ['greenyellow', '#F7BA2A', 'red'],
      points: ['greenyellow', '#F7BA2A', 'red'],//用于收集每次课程的知识点遍历生成options
      form: {
        sid: null,//课程号
        point: [],//知识点
        stem: '',//题干
        analysis: '',//解析
        answer: [{name: 'answerA', content: ''}],//答案
        mark: '',//分数
        difficulty: 0,//难度
        share:false
      },//暂时写死课程名数据
      subjectFilter: [],
      formLoading: true,
      rules: {
        gradeLevel: [
          {required: true, message: '请选择年级', trigger: 'change'}
        ],
        point: [
          {required: true, message: '请选择知识点', trigger: 'change'}
        ],
        sid: [
          {required: true, message: '请选择学科', trigger: 'change'}
        ],
        stem: [
          {required: true, message: '请输入题干', trigger: 'blur'}
        ],
        mark: [
          {required: true, message: '请输入分数', trigger: 'blur'}
        ],
        answer: [
          {required: true, message: '请选择正确答案', trigger: 'change'}
        ]
      },
      richEditor: {
        dialogVisible: false,
        object: null,
        parameterName: '',
        instance: null
      },
      questionShow: {
        qType: 0,
        dialog: false,
        question: null,
        formLoading: false
      }
    }
  },
  methods: {
    editorReady(instance) {
      this.richEditor.instance = instance
      let currentContent = this.richEditor.object[this.richEditor.parameterName]
      this.richEditor.instance.setContent(currentContent)
      // 光标定位到Ueditor
      this.richEditor.instance.focus(true)
    },
    change() {
      getKnowledge({
        sid: this.form.sid
      }).then(res => {
        this.points = res.data;
      },error=>{
        console.log('请求失败yayayay', error.message);
        this.Error1();
      })
    },
    Error1() {
      this.$notify.error({
        title: '失败',
        message: '请求失败了，请稍后重试',
        type: 'success',
        duration: 1500,
      })
    },
    inputClick(object, parameterName) {
      this.richEditor.object = object
      this.richEditor.parameterName = parameterName
      this.richEditor.dialogVisible = true
    },
    editorConfirm() {
      let content = this.richEditor.instance.getContent()
      this.richEditor.object[this.richEditor.parameterName] = content
      this.richEditor.dialogVisible = false
    },
    questionItemRemove(index) {
      this.form.items.splice(index, 1)
    },
    questionItemAdd() {
      let answer = this.form.answer;
      let newLastPrefix
      if (answer.length > 0) {
        let last = answer[answer.length - 1];
        newLastPrefix = 'answer' + String.fromCharCode(last.name.slice(6).charCodeAt() + 1)
      } else {
        newLastPrefix = 'answer' + 'A';
      }
      answer.push({name: newLastPrefix, content: ''});
    },
    submitForm() {
      var form=Object.assign(this.form);
      form.share=this.form.share==false?0:1;
      axios({
        method: "post",
        url: "http://42.193.219.14:8080/addGapFilling",
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer " + sessionStorage.getItem('token')
        },
        withCredentials: true,
        data: form
      }).then((response) => {
        console.log(response);
      });
    },
    resetForm() {
      let lastId = this.form.id
      this.$refs['form'].resetFields()
      this.form = {
        sid: null,
        stem: '',
        analysis: '',
        answer: [],
        mark: '',
        difficulty: 0
      }
      this.form.id = lastId
    },
    levelChange() {
      this.form.sid = null
      this.subjectFilter = this.subjects.filter(data => data.level === this.form.gradeLevel)
    },
    showQuestion() {
      this.questionShow.dialog = true
      this.questionShow.qType = 2
      this.questionShow.question = this.form
    },
  },
}
</script>

<style scoped>
.el-select {
  float: left;
}

.el-select:nth-of-type(n) {
  float: left;
}

.el-input {
  width: 80%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}

.el-form-item__label {
  width: 150px !important;
}

.el-form-item__content {
  margin-left: 50px !important;
}

.el-input__inner:nth-of-type(2) {
  height: 100px !important;
  overflow: auto;
}

.el-form-item {
  margin-top: 10px;
  color: greenyellow;
}
</style>